package cn.edu.tju.core.exception;

import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理参数验证异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<HttpResult<Object>> handleIllegalArgumentException(IllegalArgumentException e) {
        logger.warn("参数验证失败: {}", e.getMessage());
        HttpResult<Object> result = HttpResult.failure(ResultCodeEnum.BAD_REQUEST, e.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
    }

    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<HttpResult<Object>> handleNullPointerException(NullPointerException e) {
        logger.error("空指针异常: ", e);
        HttpResult<Object> result = HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "系统内部错误");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
    }

    /**
     * 处理运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<HttpResult<Object>> handleRuntimeException(RuntimeException e) {
        logger.error("运行时异常: ", e);
        HttpResult<Object> result = HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "系统内部错误: " + e.getMessage());
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
    }

    /**
     * 处理所有其他异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<HttpResult<Object>> handleException(Exception e) {
        logger.error("未知异常: ", e);
        HttpResult<Object> result = HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "系统内部错误");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
    }
}
